<?php
///////////////
// 必要的引用 //
//////////////

//后台菜单
require_once get_template_directory() . '/mb/codestar-framework.php';
require_once get_template_directory() . '/option/config.php';

//特殊方法
require_once get_template_directory() . '/advance/advanced-methods.php';

//允许用户自定义头像
require_once get_template_directory() . '/include/user-local-avatars.php';

//小工具缓存
require_once get_template_directory() . '/include/widget-cache.php';
///////////
// 初始化 //
///////////

/**
 * 注册菜单位置
 * @author 吕舒君
 * @DateTime  2020-04-14T13:14:12+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    无
 */
function kublog_menu()
{
    $locations = array(
        'primary' => __('主菜单', 'kbk'),
    );

    register_nav_menus($locations);
}
add_action('init', 'kublog_menu');

/**
 * 在工具栏上添加支持按钮
 * @author 吕舒君
 * @DateTime  2020-04-14T13:14:28+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    无
 */
function support()
{
    global $wp_admin_bar;

    $args = array(
        'id'    => 'goblog',
        'title' => __('酷博客作者主页', 'kbk'),
        'href'  => 'https://cszj.wang/',
    );
    $wp_admin_bar->add_menu($args);
}
add_action('wp_before_admin_bar_render', 'support', 999);

/**
 * 前台不加载语言包
 */
add_filter('locale', function ($locale) {
    $locale = (is_admin()) ? $locale : 'en_US';
    return $locale;
});

//自定义用户个人资料信息
add_filter('user_contactmethods', 'wpdaxue_add_contact_fields');
/**
 * 个人信息加强
 * @author 吕舒君
 * @DateTime  2020-05-13T21:55:54+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     array                   $contactmethods 个人信息加强
 * @return    array                                   修改数组
 */
function wpdaxue_add_contact_fields($contactmethods)
{
    $contactmethods['user_site']   = '个人网站';
    $contactmethods['user_fanc']   = '粉丝'; //粉丝，记下关注者的ID
    $contactmethods['user_follow'] = '关注别人'; //关注别人，记下被关注者的ID
    $contactmethods['user_jifen']  = '积分';
    $contactmethods['user_views']  = '总浏览量';
    return $contactmethods;
}

/**
 * 判断浏览器是否支持webp
 * @author 吕舒君
 * @DateTime  2020-07-18T11:03:32+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    boolean                  判断支持性
 */
function is_support_webp()
{
    return stristr($_SERVER['HTTP_ACCEPT'], 'image/webp') || $_SERVER['HTTP_ACCEPT'] == '*/*';
}

/**
 * 是否为手机访问
 * @author 吕舒君
 * @DateTime  2020-06-21T15:03:24+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    boolean                  是否为手机访问
 */
function is_mobile_request()
{
    $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
    $mobile_browser      = '0';
    if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
        $mobile_browser++;
    }

    if ((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') !== false)) {
        $mobile_browser++;
    }

    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        $mobile_browser++;
    }

    if (isset($_SERVER['HTTP_PROFILE'])) {
        $mobile_browser++;
    }

    $mobile_ua     = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
    $mobile_agents = array(
        'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
        'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
        'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
        'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
        'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
        'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
        'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
        'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
        'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-',
    );
    if (in_array($mobile_ua, $mobile_agents)) {
        $mobile_browser++;
    }

    if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false) {
        $mobile_browser++;
    }

    // Pre-final check to reset everything if the user is on Windows
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false) {
        $mobile_browser = 0;
    }

    // But WP7 is also Windows, with a slightly different characteristic
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false) {
        $mobile_browser++;
    }

    if ($mobile_browser > 0) {
        return true;
    } else {
        return false;
    }

}

/**
 * 注册自定义文章类型"公告"
 * @author 吕舒君
 * @DateTime  2020-04-14T13:14:52+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 */
function add_notice()
{

    $labels = array(
        'name'                  => _x('公告', 'Post Type General Name', 'kbk'),
        'singular_name'         => _x('公告', 'Post Type Singular Name', 'kbk'),
        'menu_name'             => __('公告', 'kbk'),
        'name_admin_bar'        => __('公告', 'kbk'),
        'archives'              => __('公告存档', 'kbk'),
        'attributes'            => __('公告属性', 'kbk'),
        'parent_item_colon'     => __('父公告', 'kbk'),
        'all_items'             => __('所有公告', 'kbk'),
        'add_new_item'          => __('添加新公告', 'kbk'),
        'add_new'               => __('添加新公告', 'kbk'),
        'new_item'              => __('新公告', 'kbk'),
        'edit_item'             => __('编辑公告', 'kbk'),
        'update_item'           => __('更新公告', 'kbk'),
        'view_item'             => __('预览公告', 'kbk'),
        'view_items'            => __('预览公告', 'kbk'),
        'search_items'          => __('搜索公告', 'kbk'),
        'not_found'             => __('未找到', 'kbk'),
        'not_found_in_trash'    => __('在垃圾箱内未找到你', 'kbk'),
        'featured_image'        => __('[废弃]', 'kbk'),
        'set_featured_image'    => __('[废弃]', 'kbk'),
        'remove_featured_image' => __('[废弃]', 'kbk'),
        'use_featured_image'    => __('[废弃]', 'kbk'),
        'insert_into_item'      => __('插入公告', 'kbk'),
        'uploaded_to_this_item' => __('上传至公告', 'kbk'),
        'items_list'            => __('公告列表', 'kbk'),
        'items_list_navigation' => __('公告导航', 'kbk'),
        'filter_items_list'     => __('过滤公告', 'kbk'),
    );
    $args = array(
        'label'               => __('公告', 'kbk'),
        'description'         => __('网站公告', 'kbk'),
        'labels'              => $labels,
        'supports'            => array('title', 'editor'),
        'taxonomies'          => array('category'),
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'menu_position'       => 5,
        'show_in_admin_bar'   => true,
        'show_in_nav_menus'   => true,
        'can_export'          => true,
        'has_archive'         => true,
        'rewrite'             => false,
        'exclude_from_search' => true,
        'publicly_queryable'  => true,
        'capability_type'     => 'page',
    );
    register_post_type('notice', $args);

}
add_action('init', 'add_notice', 0);

//新建说说功能
add_action('init', 'my_custom_init');
function my_custom_init()
{
    $labels = array('name' => '说说',
        'singular_name'        => '说说',
        'add_new'              => '发表说说',
        'add_new_item'         => '发表说说',
        'edit_item'            => '编辑说说',
        'new_item'             => '新说说',
        'view_item'            => '查看说说',
        'search_items'         => '搜索说说',
        'not_found'            => '暂无说说',
        'not_found_in_trash'   => '没有已遗弃的说说',
        'parent_item_colon'    => '', 'menu_name' => '说说');
    $args = array('labels' => $labels,
        'public'               => true,
        'publicly_queryable'   => true,
        'show_ui'              => true,
        'show_in_menu'         => true,
        'exclude_from_search'  => true,
        'query_var'            => true,
        'rewrite'              => true, 'capability_type' => 'post',
        'has_archive'          => false, 'hierarchical'   => false,
        'menu_position'        => null,
        'taxonomies'           => array('category', 'post_tag'),
        'supports'             => array('editor', 'author', 'title', 'custom-fields', 'comments'));
    register_post_type('shuoshuo', $args);
}

/**
 * 注册两个侧边栏位置
 */
register_sidebar(array(
    'name'          => __('侧边栏', 'kbk'),
    'id'            => 'widget_default',
    'description'   => __('显示在全站的侧边栏', 'kbk'),
    'before_widget' => '<div id="%1$s" class="%2$s mdui-panel-item mdui-panel-item-open">',
    'after_widget'  => '</div></div>',
    'before_title'  => '<div class="mdui-panel-item-header">',
    'after_title'   => '<i class="line" ></i></div><div class="mdui-panel-item-body">',
));
register_sidebar(array(
    'name'          => __('页脚侧边栏', 'kbk'),
    'id'            => 'foot_widget',
    'description'   => __('显示在页脚的侧边栏', 'kbk'),
    'before_widget' => '<div id="%1$s" class="widget %2$s">',
    'after_widget'  => '</div></div>',
    'before_title'  => '<div class="widget-header">',
    'after_title'   => '</div><div class="widget-body">',
));

///////////
//核心方法//
//////////

/**
 * 注册样式及脚本
 * @author 吕舒君
 * @DateTime  2020-04-14T13:00:54+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    无
 */
function regs()
{
    wp_enqueue_script('jqjs', 'https://lib.baomitu.com/jquery/3.5.0/jquery.min.js', array(), false, false);
    wp_enqueue_script('lazyimg-js', 'https://lib.baomitu.com/jquery.lazyload/1.9.1/jquery.lazyload.min.js', array('jqjs'), false, false);
    wp_enqueue_script('mduijs', 'https://lib.baomitu.com/mdui/0.4.3/js/mdui.min.js', array('jqjs'), false, false);
    wp_enqueue_style('mduicss', 'https://lib.baomitu.com/mdui/0.4.3/css/mdui.min.css');
    wp_enqueue_script('jqscrolljs', get_template_directory_uri() . '/assert/js/scroll.js', array('jqjs'), false, false);
    wp_enqueue_style('theme', get_template_directory_uri() . '/style.css');
    wp_enqueue_script('main-js', get_template_directory_uri() . '/assert/js/main.js', array('mduijs', 'jqjs', 'lazyimg-js', 'jqscrolljs'), false, false);
    wp_localize_script('main-js', 'i', array('ajaxurl' => admin_url('admin-ajax.php')));
    wp_enqueue_style('npcss', 'https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css');
    wp_enqueue_script('npjs', 'https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js', array('jqjs'), false, false);
    wp_enqueue_style('bxcss', 'https://lib.baomitu.com/bxslider/4.2.15/jquery.bxslider.min.css');
    wp_enqueue_script('bsjs', 'https://lib.baomitu.com/bxslider/4.2.15/jquery.bxslider.min.js', array('jqjs'), false, false);
    if (is_singular(array('post', 'page'))) {
        wp_enqueue_script('verify',get_template_directory_uri().'/assert/js/verify.js');
        wp_enqueue_script('highlight-js', "https://lib.baomitu.com/highlight.js/9.15.10/highlight.min.js");
        wp_enqueue_style('highlight-css', "https://lib.baomitu.com/highlight.js/9.15.10/styles/an-old-hope.min.css");
        wp_enqueue_script('spotlight-js', get_template_directory_uri() . '/assert/js/spotlight.js');
        wp_enqueue_script('ckeditor', 'https://lib.baomitu.com/ckeditor5/20.0.0/ckeditor.js', false, false);
        wp_enqueue_style('post-css', get_template_directory_uri() . '/assert/css/type.css');
        wp_enqueue_script('post-js', get_template_directory_uri() . '/assert/js/post.js', array('mduijs', 'main-js'), false, false);
        wp_localize_script('post-js', 'i', array('ajaxurl' => admin_url('admin-ajax.php')));
    } elseif (is_front_page() || is_home()) {
        wp_enqueue_script('index-js', get_template_directory_uri() . '/assert/js/index.js', array('mduijs', 'main-js'), false, false);
        wp_localize_script('index-js', 'i', array('ajaxurl' => admin_url('admin-ajax.php')));
    }
    if (kbk('site-velocity-analysis')) {
        wp_enqueue_script('analysis-js', get_template_directory_uri() . '/assert/js/analysis.js', array(), false, false);
    }
    if (kbk('protect-f12')) {
        wp_enqueue_script('protect-f12-js', get_template_directory_uri() . '/assert/js/protect-f12.js', array(), false, false);
    }
    if (kbk('title-roll-enable')) {
        wp_add_inline_script('jqjs', '
            setTimeout(function() {
                newtitle();
            },' . kbk('title-roll-delay') . ');
            function newtitle() {
                var text = document.title
                var timerID
                if (text.length > ' . kbk('title-roll-limit') . ') {
                    document.title = text.substring(1, text.length) + text.substring(0, 1);
                    text = document.title.substring(0, text.length);
                    timerID = setTimeout("newtitle()", ' . kbk('title-roll-num') . ')
                }
            }
        ');
    }
    if (kbk('font-enable')){
    	wp_add_inline_style('mduicss','
    	@font-face {
	        font-family: "ThemeFont";
	        src: url(\''.get_stylesheet_directory_uri().'/font/Barlow-Regular.ttf\');
	        font-display: swap;
	    }
    	');
    }
    if(kbk('pop-up-text-enable'))
    {
        $s;
        if (kbk('pop-up-text-list') != null):
            foreach (kbk('pop-up-text-list') as $key => $value) {
                $s=$s. '"' . kbk('pop-up-text-list')[$key]['pop-up-text-list-item'] . '"' . ',';
            }
        endif;
        wp_add_inline_script('jqjs', '
            var a_idx = 0;
            jQuery(document).ready(function($) {
                $("body").click(function(e) {
                var a = new Array('.$s.');
                var $i = $("<span/>").text(a[a_idx]);
                a_idx = (a_idx + 1)% a.length;
                var x = e.pageX, y = e.pageY;
                $i.css({"z-index" : 999999999999999999999999999999999999999999999999999999999999999999999,
                    "top" : y - 20,
                    "left" : x,
                    "position" : "absolute",
                    "font-weight" : "bold",
                    "color" : "#ff6651"
                    });
                $("body").append($i);
                    $i.animate({
                        "top" : y - 180,
                        "opacity" : 0
                    }, 1500, function() {
                        $i.remove();
                    });
                });
            });
        ');
    }
    if(kbk('is_site_notify')&&is_home()){
        wp_add_inline_script('mainjs','
            $(function(){
                var inst = new mdui.Dialog("#site-notify", {
                    "history":false
                });
                inst.open();
                inst.addEventListener("confirm.mdui.dialog", function () {
                    log("Dialog Confirm");
                });
            });
        ');
    }
}
add_action('wp_enqueue_scripts', 'regs');

/**
 * 注册编辑器样式
 */
add_editor_style('editor-style.css', '1.0');

/**
 * 前端加载自己的JQuery库
 * @author 吕舒君
 * @DateTime  2020-04-14T13:04:35+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    无
 */
function disableJQ()
{
    wp_deregister_script('jquery');
}
add_action('wp_enqueue_scripts', 'disableJQ', 1);

/**
 * 获取设置字段的值
 * @author 吕舒君
 * @DateTime  2020-04-14T13:05:58+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     string 设置字段
 * @param     object 字段没有值时的默认返回值
 * @return    string 该字段的值
 */
function kbk($option = '', $default = null)
{
    $options = get_option('kbk');
    return (isset($options[$option])) ? $options[$option] : $default;
}

/**
 * 获取并**输出**设置字段的值
 * @author 吕舒君
 * @DateTime  2020-04-14T13:10:14+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     string 设置字段
 * @param     object 字段没有值时的默认返回值
 * @return    无
 */
function kbk_e($option = '', $default = null)
{
    $options = get_option('kbk');
    echo (isset($options[$option])) ? $options[$option] : $default;
}

/**
 * 使插入的图片自动链接至自身
 */
update_option('image_default_link_type', 'file');

//主题更新
// require_once(TEMPLATEPATH . '/include/theme-update-checker.php');
// $wpdaxue_update_checker = new ThemeUpdateChecker(
//     'KUWP', //主题名字
//     'http://www.xxx.com/themes/info.json'  //info.json 的访问地址
// );

///////////
//图片裁剪//
///////////

function getThumb($url, $w, $h)
{
    if (is_support_webp() != false) {
        return $url . "?imageMogr2/thumbnail/{$w}x{$h}/format/webp";
    }
    return $url . "?imageMogr2/thumbnail/{$w}x{$h}";
}

function getThumbByW($url, $w)
{
    if (is_support_webp() != false) {
        return $url . "?imageMogr2/thumbnail/{$w}x/format/webp";
    }
    return $url . "?imageMogr2/thumbnail/{$w}x";
}

function getThumbByH($url, $h)
{
    if (is_support_webp() != false) {
        return $url . "?imageMogr2/thumbnail/x{$h}/format/webp";
    }
    return $url . "?imageMogr2/thumbnail/x{$h}";
}

///////////
//文章相关//
///////////

/**
 * 首页分页
 * @author 吕舒君
 * @DateTime  2020-04-14T15:18:16+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    输出分页后目录结构
 */
function weihuan_paginate()
{
    $args = array(
        'prev_next' => 0,
        'format'    => '?paged=%#%',
        'mid_size'  => 2,
        'current'   => max(1, get_query_var('paged')),
        'prev_next' => true,
        'prev_text' => __('上一页', 'kbk'),
        'next_text' => __('下一页', 'kbk'),
    );
    $page_arr = paginate_links($args);
    if ($page_arr) {
        echo '<div class="pages">' . $page_arr . '</div>';
    }
}

/////////////
// 部分优化 //
////////////

/**
 * 允许中文用户名注册
 * @author 吕舒君
 * @DateTime  2020-05-04T20:52:10+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     string                   $username     用户名
 * @param     string                   $raw_username 限制用户名
 * @param     bool                   $strict       是否严格
 * @return    无                                 无
 */
if (kbk('chinese-registered-user-name')) {
    function ludou_sanitize_user($username, $raw_username, $strict)
    {
        $username = wp_strip_all_tags($raw_username);
        $username = remove_accents($username);
        $username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $username);
        $username = preg_replace('/&.+?;/', '', $username);
        if ($strict) {
            $username = preg_replace('|[^a-z\p{Han}0-9 _.\-@]|iu', '', $username);
        }
        $username = trim($username);
        $username = preg_replace('|\s+|', ' ', $username);
        return $username;
    }

    add_filter('sanitize_user', 'ludou_sanitize_user', 10, 3);
}

if (!function_exists('Baidu_Submit')) {
    /**
     * 百度推送
     * @author 吕舒君
     * @DateTime  2020-07-30T09:16:39+0800
     * @email     Lvshujun****@***.com
     * @copyright 吕舒君                      2020
     * @param     integer                   $post_ID 文章ID
     */
    function Baidu_Submit($post_ID)
    {
        $WEB_TOKEN  = kbk('baidu-site-ID');
        $WEB_DOMAIN = get_option('home');
        if (get_post_meta($post_ID, 'Baidusubmit', true) == 1) {
            return;
        }

        $url     = get_permalink($post_ID);
        $api     = 'https://data.zz.baidu.com/urls?site=' . $WEB_DOMAIN . '&token=' . $WEB_TOKEN;
        $request = new WP_Http;
        $result  = $request->request($api, array('method' => 'POST', 'body' => $url, 'headers' => 'Content-Type: text/plain'));
        $result  = json_decode($result['body'], true);
        if (array_key_exists('success', $result)) {
            add_post_meta($post_ID, 'Baidusubmit', 1, true);
        }
    }
    add_action('publish_post', 'Baidu_Submit', 0);
    add_action('update_post', 'Baidu_Submit', 0);
}

/**
 * 自定义文章摘要长度
 * @author 吕舒君
 * @DateTime  2020-04-14T15:36:39+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     摘要长度(此长度不会生效)
 * @return    摘要长度
 */
function custom_excerpt_length($length)
{
    return get_option('kbk')['summarynum'];
}
add_filter('excerpt_length', 'custom_excerpt_length', 999);

//自定义登陆logo的url
add_filter('login_headerurl', function () {return home_url();});
add_filter('login_headertext', function () {return get_bloginfo('name');});

/**
 * 外链跳转
 * @author zhangge
 * @DateTime  2020-07-22T10:13:54+0800
 * @email     Lvshujun****@***.com
 * @copyright zhangge                      2020
 * @param     string                   $content 原内容
 * @return    string                            吸引改后内容
 */
function the_content_nofollow($content)
{
    preg_match_all('/<a(.*?)href="(.*?)"(.*?)>/', $content, $matches);
    if ($matches) {
        foreach ($matches[2] as $val) {
            if (strpos($val, '://') !== false && strpos($val, home_url()) === false && !preg_match('/\.(jpg|jepg|png|ico|bmp|gif|tiff)/i', $val)) {
                $content = str_replace("href=\"$val\"", "href=\"" . get_template_directory_uri() . "/go.php?url=" . base64_encode($val) . "\" rel=\"nofollow\" target=\"_blank\"", $content); //非伪静态设置
            }
        }
    }
    return $content;
}
add_filter('the_content', 'the_content_nofollow', 999);
add_filter('comment_text', 'the_content_nofollow', 99);
add_filter('get_comment_author_link', 'the_content_nofollow', 5);

/**
 * 修改摘要结尾
 * @author 吕舒君
 * @DateTime  2020-04-14T15:37:26+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    摘要结尾
 */
function excerpt_more()
{
    return "...";
}
add_filter('excerpt_more', 'excerpt_more');

/**
 * 去除标点转换
 */
remove_filter('the_content', 'wptexturize');

/////////////
// 相关方法 //
////////////

/**
 * 获取文章中的第一张图片
 * @author 吕舒君
 * @DateTime  2020-04-14T15:19:35+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    string 图片地址
 */
function catch_that_image()
{
    global $post;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img*.+src=[\'"]([^\'"]+)[\'"].*>/iU', wp_unslash($post->post_content), $matches);
    if (empty($output)) {
        $first_img = get_option('kbk')['defaultimg'];
    } else {
        $first_img = $matches[1][0];
    }
    return $first_img;
}

/**
 * 根据文章ID获取文章第一张图片
 * @author 吕舒君
 * @DateTime  2020-04-14T15:20:16+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     int ID
 * @return    string 图片地址
 */
function catch_imgByID($id)
{
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img*.+src=[\'"]([^\'"]+)[\'"].*>/iU', wp_unslash(get_post($id)->post_content), $matches);
    if (empty($output)) {
        $first_img = get_option('kbk')['defaultimg'];
    } else {
        $first_img = $matches[1][0];
    }
    return $first_img;
}

/**
 * 根据标题获得文章ID
 * @author 吕舒君
 * @DateTime  2020-04-14T15:18:50+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     string 标题
 * @return    int 文章ID
 */
function get_post_idByTitle($title)
{
    $post = get_page_by_title($title, OBJECT, 'post');
    return $post->ID;
}

/**
 * 判断文章是否有图片
 * @author 吕舒君
 * @DateTime  2020-04-14T15:35:03+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    boolean
 */
function is_has_image()
{
    global $post;
    if (has_post_thumbnail()) {
        return true;
    }

    $content = $post->post_content;
    preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
    if (!empty($strResult[1])) {
        return true;
    }

    return false;
}

function get_holder_img($w, $h, $word)
{
    return get_template_directory_uri() . '/holder.php/?w=' . $w . '&h=' . $h . '&text=' . $word . '&random=yes';
}

/////////////
// 相关功能 //
////////////

/**
 * 自动转换文章图片为webp
 * @author 吕舒君
 * @DateTime  2020-07-18T11:02:50+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     array                   $matches 图片参数
 * @return    string                            修改后的图片
 */
function converse_webp($matches)
{
    if (is_support_webp() != false) {
        return $matches[1] . $matches['2'] . '?imageMogr2/format/webp';
    } else {
        return $matches[1] . $matches['2'];
    }
}

/**
 * 图片添加水印
 * @author 吕舒君
 * @DateTime  2020-07-18T11:16:44+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     array                   $matches 图片参数
 * @param     string                   $text    修改后的图片
 */
function add_watermark($matches, $text = 'C#之家')
{
    return $matches[1] . $matches['2'] . '|watermark/2/text/' . base64_encode($text) . '/fill/' . base64_encode('simkai.ttf') . '/fontsize/20/dissolve/50/gravity/northeast/dx/20/dy/20/batch/1/degree/45';
}

/**
 * 优化文章内图片
 * @author 吕舒君
 * @DateTime  2020-07-18T11:04:26+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     string                   $content 原文章内容
 * @return    string                            现文章内容
 */
function content_img_filter($content)
{
    global $post;
    $content = preg_replace_callback("/(<img[^>]*src *= *[\"']?)([^\"']*)/i", 'converse_webp', $content);
    $content = preg_replace_callback("/(<img[^>]*src *= *[\"']?)([^\"']*)/i", 'add_watermark', $content);
    return $content;
}
add_filter('the_content', 'content_img_filter');

/**
 * 关键词排序
 * @author 吕舒君
 * @DateTime  2020-04-14T15:38:46+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     关键词a
 * @param     关键词b
 * @return    排序(-1或1)
 */
function tag_sort($a, $b)
{
    if ($a->name == $b->name) {
        return 0;
    }

    return (strlen($a->name) > strlen($b->name)) ? -1 : 1;
}

/**
 * 文章目录索引
 * @author 吕舒君
 * @DateTime  2020-04-15T14:55:28+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     string                   $content 文章内容
 * @return    string                            被修改后的内容
 */
function article_index()
{
    if (is_single()) {
        $matches = array();
        $ul_li   = '';
        $mulu    = '';
        $r       = '/<h([2-6]).*?\>(.*?)<\/h[2-6]>/is';
        $content = get_the_content();
        if (preg_match_all($r, $content, $matches)) {
            foreach ($matches[1] as $key => $value) {
                $title   = trim(strip_tags($matches[2][$key]));
                $content = str_replace($matches[0][$key], '<h' . $value . ' id="title-' . $key . '">' . $title . '</h2>', $content);
                $ul_li .= '<li style="text-indent: ' . ($value - 2) . 'em;" ><a href="#title-' . $key . '" title="' . $title . '">' . $title . "</a></li>\n";
            }
            $mulu = "\n<div id=\"article-index\">
            <ol id=\"index-ul\">\n" . $ul_li . "</ol>
            </div>\n";
        }
    }
    return $mulu;
}

/**
 * 文章标题加ID
 * @author 吕舒君
 * @DateTime  2020-04-16T09:03:51+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     string                   $content 文章内容
 * @return    string                            文章修改后内容
 */
function article_index_title($content)
{
    $matches = array();
    $r       = '/<h([2-6]).*?\>(.*?)<\/h[2-6]>/is';
    if (is_single() && preg_match_all($r, $content, $matches)) {
        foreach ($matches[1] as $key => $value) {
            $title   = trim(strip_tags($matches[2][$key]));
            $content = str_replace($matches[0][$key], '<h' . $value . ' id="title-' . $key . '">' . $title . '</h2>', $content);
        }
    }
    return $content;
}
add_filter('the_content', 'article_index_title');

/**
 * 去除评论链接
 * @author 吕舒君
 * @DateTime 2020-07-17T21:56:51+0800
 * @return   无                   无
 */
function no_link_in_comment()
{
    $url    = get_comment_author_url();
    $author = get_comment_author();
    if (empty($url) || 'http://' == $url) {
        return $author;
    } else {
        return "<a target='_blank' href='$url' rel='external nofollow' class='url'>$author</a>";
    }
}
add_filter('get_comment_author_link', 'no_link_in_comment');

/**
 * 关键词自动添加链接
 * @author 吕舒君
 * @DateTime  2020-04-14T15:39:13+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     文章内容
 * @return    被修改后的文章内容
 */
function tag_link($content)
{
    $match_num_from = 1; //一个标签少于几次不链接
    $match_num_to   = 1; //一个标签最多链接几次
    $ex_word        = "";
    $posttags       = get_the_tags();
    if ($posttags) {
        usort($posttags, "tag_sort");
        foreach ($posttags as $tag) {
            $link    = get_tag_link($tag->term_id);
            $keyword = $tag->name;
            //链接代码
            $cleankeyword = stripslashes($keyword);
            $url          = "<a href=\"$link\" title=\"" . str_replace('%s', addcslashes($cleankeyword, '$'), __('更多关于 %s 的文章')) . "\"";
            $url .= ' target="_blank"';
            $url .= ">" . addcslashes($cleankeyword, '$') . "</a>";
            $limit = rand($match_num_from, $match_num_to);
            //不链接代码
            $content      = preg_replace('|(<a[^>]+>)(.*)<pre.*?>(' . $ex_word . ')(.*)<\/pre>(</a[^>]*>)|U' . $case, '$1$2%&&&&&%$4$5', $content);
            $content      = preg_replace('|(<img)(.*?)(' . $ex_word . ')(.*?)(>)|U' . $case, '$1$2%&&&&&%$4$5', $content);
            $cleankeyword = preg_quote($cleankeyword, '\'');
            $regEx        = '\'(?!((<.*?)|(<a.*?)))(' . $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
            $content      = preg_replace($regEx, $url, $content, $limit);
            $content      = str_replace('%&&&&&%', stripslashes($ex_word), $content);
        }
    }
    return $content;
}
add_filter('the_content', 'tag_link', 1);

/**
 * 输出点赞按钮
 * @author 吕舒君
 * @DateTime 2020-07-17T21:59:12+0800
 * @param    interger                   $post_id      文章ID
 * @return   无                   无
 */
function likebutton($post_id)
{
    // 将 _like_count 改成 likes
    if (metadata_exists('post', $post_id, 'likes')) {
        $like_count = get_post_meta($post_id, 'likes', true) ?: '0';
    } elseif (metadata_exists('post', $post_id, '_like_count')) {
        $like_count = get_post_meta($post_id, '_like_count', true) ?: '0';
        update_post_meta($post_id, 'likes', $like_count);
        delete_post_meta($post_id, '_like_count');
    } else {
        $like_count = 0;
    }

    $liked = isset($_COOKIE['liked_' . $post_id]) ? 'liked' : '';

    echo '<button href="javascript:;" data-id="' . $post_id . '" class="mdui-btn mdui-btn-raised like ' . $liked . '"><i class="mdui-icon-left mdui-icon material-icons">&#xe8dc;</i><span class="count">' . $like_count . '</span></button>';
}

////////
//ajax//
////////

/**
 * 处理点赞ajax
 * @author 吕舒君
 * @DateTime 2020-07-17T22:00:16+0800
 * @return   无                   无
 */
function post_like_ajax_handler()
{
    global $wpdb, $post;
    if ($post_id = $_POST["post_id"]) {
        if (metadata_exists('post', $post_id, 'likes')) {
            $like_count = get_post_meta($post_id, 'likes', true) ?: '0';
        } elseif (metadata_exists('post', $post_id, '_like_count')) {
            $like_count = get_post_meta($post_id, '_like_count', true) ?: '0';
            update_post_meta($post_id, 'likes', $like_count);
            delete_post_meta($post_id, '_like_count');
        } else {
            $like_count = 0;
        }

        $expire = time() + 99999999;
        $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;

        setcookie('liked_' . $post_id, $post_id, $expire, '/', $domain, false);
        if (!$like_count || !is_numeric($like_count)) {
            update_post_meta($post_id, 'likes', 1);
        } else {
            update_post_meta($post_id, 'likes', ($like_count + 1));
        }
        ;

        echo get_post_meta($post_id, 'likes', true);
    }

    exit;
}
add_action('wp_ajax_nopriv_post_like', 'post_like_ajax_handler');
add_action('wp_ajax_post_like', 'post_like_ajax_handler');

/**
 * 处理点赞ajax
 * @author 吕舒君
 * @DateTime 2020-07-17T22:00:16+0800
 * @return   无                   无
 */
function postlist_ajax_handler()
{
    $args = array(
        'orderby'        => 'date',
        'paged'          => (int) $_POST['p'],
        'posts_per_page' => 5,
    );
    $the_query = new WP_Query($args);
    if ($the_query->have_posts()):
        while ($the_query->have_posts()):
            $the_query->the_post();
            ?>
                                            <div class="<?php echo $_POST['p'] . 'PPP ' ?>post-card mdui-card mdui-m-b-2 mdui-hoverable">
                                                <div class="mdui-card-header">
                                                    <img alt="作者头像" class="mdui-card-header-avatar" src="<?php echo json_get_avatar_url(get_avatar(get_the_author_meta('ID'), 50)); ?>" />
                                                    <div class="mdui-card-header-title">
                                                        <?php echo get_the_author_meta("display_name"); ?>
                                                    </div>
                                                    <div class="mdui-card-header-subtitle">
                                                        <?php the_author_description();?>
                                                    </div>
                                                </div>
                                                <div class="mdui-card-media">
                                                    <?php if (is_has_image() || kbk('showdefaultthumb')): ?>
                                                    <img src='<?php echo get_template_directory_uri() . '/assert/img/loading.png' ?>' data-original='
                                                    <?php echo getThumb(catch_that_image(), 210, 160) ?>' alt="[
                                                    <?php the_title();?>]的缩略图"/>
                                                    <?php endif;?>
                                    <div class="mdui-card-menu">
                                        <button class="mdui-btn mdui-btn-icon mdui-text-color-white"><i class="mdui-icon material-icons">share</i></button>
                                    </div>
                                </div>
                                <div class="post-card-content">
                                    <div class="mdui-card-primary">
                                        <div class="mdui-card-primary-title"><a href='<?php the_permalink();?>'>
                                                <?php the_title();?></a></div>
                                        <div class="mdui-card-primary-subtitle"><i class="mdui-icon material-icons">&#xe5c3;</i>
                                            <?php $category = get_the_category();
        echo '<a href="' . get_category_link($category[0]->term_id) . '">' . $category[0]->cat_name . '</a>'?><i class="mdui-icon material-icons">&#xe855;</i>
                                            <?php echo __time(get_the_time("c")); ?>
                                        </div>
                                    </div>
                                    <div class="mdui-card-content">
                                        <?php the_excerpt();?>
                                    </div>
                                    <div class="mdui-card-actions">
                                        <button class="mdui-btn mdui-ripple"><a href='<?php the_permalink();?>'>去看看</a></button>
                                        <button class="mdui-btn mdui-btn-icon mdui-float-right"><i class="mdui-icon material-icons">expand_more</i></button>
                                    </div>
                                </div>
                            </div>
                            <?php
endwhile;
    endif;
    wp_reset_postdata();
    exit;
}
add_action('wp_ajax_nopriv_post_list', 'postlist_ajax_handler');
add_action('wp_ajax_post_list', 'postlist_ajax_handler');

/**
 * ajax获取文章图片
 * @author 吕舒君
 * @DateTime  2020-07-29T08:28:00+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    无                   无
 */
function get_post_img()
{
    $imgsrc = get_post_meta($_POST['id'], 'postimgsrc', true);
    if (!$imgsrc || empty($imgsrc)) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $_POST['url']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $output = curl_exec($ch);
        $arr    = json_decode($output, true);
        $img    = $arr['data']['src'];
        curl_close($ch);
        //add_post_meta($post->id, "postimgsrc", $img,false);
        update_post_meta($_POST['id'], 'postimgsrc', $img);
        echo $img;
    } else {
        echo $imgsrc;
    }
    exit;
}
add_action('wp_ajax_nopriv_imgsrc', 'get_post_img');
add_action('wp_ajax_imgsrc', 'get_post_img');

/////////////
// 文章评论 //
////////////

/**
 * 获取评论人数
 * @author 吕舒君
 * @DateTime  2020-04-14T15:42:20+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     integer 文章ID
 * @param     integer
 * @return    integer 评论人数
 */
function zfunc_comments_users($postid = 0, $which = 0)
{
    $comments = get_comments('status=approve&type=comment&post_id=' . $postid);
    if ($comments) {
        $i            = 0;
        $j            = 0;
        $commentusers = array();
        foreach ($comments as $comment) {
            ++$i;
            if ($i == 1) {
                $commentusers[] = $comment->comment_author_email; ++$j;
            }
            if (!in_array($comment->comment_author_email, $commentusers)) {
                $commentusers[] = $comment->comment_author_email;
                ++$j;
            }
        }
        $output = array($j, $i);
        $which  = ($which == 0) ? 0 : 1;
        return $output[$which];
    }
    return 0;
}

/**
 * 用css方法添加评论楼层
 * @author 吕舒君
 * @DateTime  2020-04-14T15:39:47+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @return    无
 */
function comment_floor_css()
{
    global $wp_query;
    if (is_singular()) {
        global $post;
        $comments = get_comments(array(
            'post_id' => get_the_ID(),
            'orderby' => 'comment_date_gmt',
            'order'   => 'ASC',
            'status'  => 'all',
        ));
        $page = get_query_var('cpage') ? get_query_var('cpage') : get_comment_pages_count($comments);
        echo '<style id="comment-style">
        #comment{
            counter-reset:comment-floor ' . ($page - 1) * get_query_var('comments_per_page') . '
        }
        #comment > .comment{
            position:relative;
        }
        #comment > .comment:before{
            content:"#"counter(comment-floor, decimal);
            counter-increment:comment-floor;
            font-size: 48px;
            position:absolute;
            top:10px;
            right:0;
            color:rgba(0,169,227,0.2);
            font-style: italic;
            font-weight: 700;
        }</style>';
    }
}
add_action('wp_head', 'comment_floor_css', 10);

/**
 * 评论时添加@...
 * @author 吕舒君
 * @DateTime  2020-04-14T15:41:12+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     string 评论文本
 * @param     string 评论对象
 * @return    string 修改后的评论文本
 */
function ludou_comment_add_at($comment_text, $comment = '')
{
    if ($comment->comment_parent > 0) {
        $comment_text = '@<a href="#comment-' . $comment->comment_parent . '">' . get_comment_author($comment->comment_parent) . '</a> ' . $comment_text;
    }

    return $comment_text;
}
add_filter('comment_text', 'ludou_comment_add_at', 20, 2);

/**
 * 文章评论列表
 * @author 吕舒君
 * @DateTime  2020-04-14T15:43:13+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     评论
 * @param     参数
 * @param     深度
 * @return    评论html结构
 */
function comment_list($comment, $args, $depth)
{
    $GLOBALS['comment'] = $comment;?>
    <div class="comment" id="comment-<?php comment_ID();?>">
        <div class="comment-wrapper">
            <img class="avatar" src="" data-original="<?php echo get_avatar_url_(48, 48); ?>">
            <div class="bubble comment-info" style="display: inline-block;vertical-align: top;">
                <div class="comment-text">
                    <?php if ($comment->comment_approved == '0'): ?>
                    <em>你的评论正在审核，稍后会显示出来！</em><br />
                    <?php endif;?>
                    <?php comment_text();?>
                </div>
            </div>
            <?php printf('<div class="comment-mate"><div class="mdui-chip"><span class="mdui-chip-title">%s</span></div>', get_comment_reply_link(array_merge($args, array('reply_text' => '回复', 'depth' => $depth, 'max_depth' => $args['max_depth']))));?>
            <?php edit_comment_link('修改', '<div class="mdui-chip"><span class="mdui-chip-title">', '</span></div>');?>
            <?php printf('<div class="mdui-chip"><span class="mdui-chip-title author-name">%s</span></div>', get_comment_author_link());?>
            <?php printf('<div class="mdui-chip"><span class="mdui-chip-title">%s</span></div></div>', get_comment_time('Y-m-d H:i'));?>

        </div>
    </div>
    <?php
}

//为部分内容加密
function e_secret($atts, $content = null)
{
    extract(shortcode_atts(array('pwd' => null), $atts));
    if (isset($_POST['pwd']) && $_POST['pwd'] == $key) {
        return '<div class="e-secret">' . $content . '</div>';
    } else {
        return '
        <form class="post-password-form" action="' . get_permalink() . '" method="post" name="e-secret">
            <label for="pwbox-142">输入密码查看加密内容：
                <input type="password" name="pwd" size="20" />
            </label>
            <input type="submit" class="euc-y-s" value="确定" />
        </form>';
    }
}
add_shortcode('secret', 'e_secret');

///////////
//用户中心//
///////////
/////获取作者关注 的数
function get_guanzu($uid)
{
    $author_follow = get_user_meta($uid, 'user_follow'); //关注
    if (empty($author_follow)) {
        $num1 = 0;
    } else {
        if ($author_follow[0] == '') {
            $num1 = 0;
        } else {
            $follows = explode(",", $author_follow[0]);
            $num1    = !empty($follows) ? count($follows) : 0;
        }
    }
    return $num1;
}

//获取作者粉丝数
function get_fanc($uid)
{
    $author_follow = get_user_meta($uid, 'user_fanc'); //关注
    if (empty($author_follow)) {
        $num1 = 0;
    } else {
        if ($author_follow[0] == '') {
            $num1 = 0;
        } else {
            $follows = explode(",", $author_follow[0]);
            $num1    = !empty($follows) ? count($follows) : 0;
        }
    }
    return $num1;
}

//获取作者积分
function get_jefen($uid)
{
    $user_jifen = get_user_meta($uid, 'user_jifen');
    if (empty($user_jifen)) {
        $num = 0;
    } else {
        $num = ($user_jifen[0] == '') ? 0 : $user_jifen[0];
    }
    return $num;
}

//获取作者文章总浏览量
function get_post_views($uid)
{
    $user_views = get_user_meta($uid, 'user_views');
    if (empty($user_views)) {
        $num = 0;
    } else {
        $num = ($user_views[0] == '') ? 0 : $user_views[0];
    }
    return $num;
}

//在用户登录时，创建一个新字段存储用户登录时间
function insert_last_login($login)
{
    global $user_id;
    date_default_timezone_set(PRC); // 纠正8小时时差
    $user = get_userdatabylogin($login);
    update_user_meta($user->ID, 'last_login', date('Y-m-d H:i:s'));
}
add_action('wp_login', 'insert_last_login');

///////////
//速度优化//
///////////

/**
 * 移除网址猜测
 * @author 吕舒君
 * @DateTime  2020-07-29T08:19:46+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     string                   $url 当前网址
 * @return    string                        当前网址
 */
function stop_guessing($url)
{
    if (is_404()) {
        return false;
    }
    return $url;
}
add_filter('redirect_canonical', 'stop_guessing');

/**
 * 移除文件版本号
 * @author 吕舒君
 * @DateTime  2020-07-29T08:20:59+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     string                   $src 文件网址
 * @return    string                        修改后的文件网址
 */
function remove_cssjs_ver($src)
{
    if (strpos($src, 'ver=')) {
        $src = remove_query_arg('ver', $src);
    }

    return $src;
}
add_filter('style_loader_src', 'remove_cssjs_ver', 999);
add_filter('script_loader_src', 'remove_cssjs_ver', 999);

//禁止前端管理栏
add_filter('show_admin_bar', '__return_false');

//去除s.w.org
remove_action('wp_head', 'wp_resource_hints', 2);

//去除版本号
remove_action('wp_head', 'wp_generator');

//移除离线编辑器接口
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');

//去除表情
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
add_filter('emoji_svg_url', '__return_false');
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); //清除前后文信息
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3); //清除feed信息
remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);

remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
remove_action('wp_head', 'wp_oembed_add_discovery_links', 10);
remove_action('wp_head', 'rel_canonical');
remove_action('wp_head', 'locale_stylesheet');

/**
 * 移除dns预读取
 * @author 吕舒君
 * @DateTime  2020-07-29T08:23:03+0800
 * @email     Lvshujun****@***.com
 * @copyright 吕舒君                      2020
 * @param     [type]                   $hints         [description]
 * @param     [type]                   $relation_type [description]
 * @return    [type]                                  [description]
 */
function remove_dns_prefetch($hints, $relation_type)
{
    if ('dns-prefetch' === $relation_type) {
        return array_diff(wp_dependencies_unique_hosts(), $hints);
    }

    return $hints;
}
add_filter('wp_resource_hints', 'remove_dns_prefetch', 10, 2);

//移除json
remove_action('wp_head', 'rest_output_link_wp_head', 999);

add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');
remove_action('wp_head', 'rest_output_link_wp_head', 10);
remove_action('wp_head', 'wp_oembed_add_discovery_links', 10);

if (kbk('gutenberg-editor')) {
    /**
     * 移除古腾堡编辑器
     * @author 吕舒君
     * @DateTime  2020-07-29T08:22:33+0800
     * @email     Lvshujun****@***.com
     * @copyright 吕舒君                      2020
     * @return    无                   无
     */
    function fanly_remove_block_library_css()
    {
        if (!is_admin() && kbk('gutenberg-editor')) {
            wp_dequeue_style('wp-block-library');
        }
    }
    add_action('wp_enqueue_scripts', 'fanly_remove_block_library_css', 100);
    add_filter('use_block_editor_for_post', '__return_false');
}

//[废弃]
// if(kbk('no-feed'))
// {
//     // 删除 wp_head 输入到模板中的feed地址链接
//     add_action( 'wp_head', 'wpse33072_wp_head', 1 );
//     function wpse33072_wp_head() {
//         remove_action( 'wp_head', 'feed_links', 2 );
//         remove_action( 'wp_head', 'feed_links_extra', 3 );
//     }

//     foreach( array( 'rdf', 'rss', 'rss2', 'atom' ) as $feed ) {
//         add_action( 'do_feed_' . $feed, 'wpse33072_remove_feeds', 1 );
//     }
//     unset( $feed );

//     // 当执行 do_feed action 时重定向到首页
//     function wpse33072_remove_feeds() {
//         wp_redirect( home_url(), 302 );
//         exit();
//     }

//     // 删除feed的重定向规则
//     add_action( 'init', 'wpse33072_kill_feed_endpoint', 99 );

//     function wpse33072_kill_feed_endpoint() {
//         global $wp_rewrite;
//         $wp_rewrite->feeds = array();

//         // 运行一次后，记得删除下面的代码
//         flush_rewrite_rules();
//     }
// }

////////////
//全站cdn//
///////////
function do_cdnrewrite_ob_start()
{
    if (kbk('cdn-enable') == true) {
        $rewriter = new FocusCDNRewriteWordpress();
        $rewriter->register_as_output_buffer();
    }
}
add_action('template_redirect', 'do_cdnrewrite_ob_start');

class FocusCDNRewriteWordpress extends FocusCDNRewrite
{
    public function __construct()
    {
        $excl_tmp = kbk('cdn-exclude');
        $excludes = array_map('trim', explode('|', $excl_tmp));

        parent::__construct(
            home_url(),
            kbk('cdn-remote'),
            'wp-content,wp-includes',
            $excludes,
            !!''
        );
    }
    public function register_as_output_buffer()
    {
        if ($this->blog_url != kbk('cdn-remote')) {
            ob_start(array(&$this, 'rewrite'));
        }
    }

}

class FocusCDNRewrite
{
    public $blog_url     = null;
    public $cdn_url      = null;
    public $include_dirs = null;
    public $excludes     = array();
    public $rootrelative = false;

    public function __construct($blog_url, $cdn_url, $include_dirs, array $excludes, $root_relative)
    {
        $this->blog_url     = $blog_url;
        $this->cdn_url      = $cdn_url;
        $this->include_dirs = $include_dirs;
        $this->excludes     = $excludes;
        $this->rootrelative = $root_relative;
    }

    protected function exclude_single(&$match)
    {
        foreach ($this->excludes as $badword) {
            if (stristr($match, $badword) != false) {
                return true;
            }
        }
        return false;
    }

    protected function rewrite_single(&$match)
    {
        if ($this->exclude_single($match[0])) {
            return $match[0];
        } else {
            if (!$this->rootrelative || strstr($match[0], $this->blog_url)) {
                return str_replace($this->blog_url, $this->cdn_url, $match[0]);
            } else {
                return $this->cdn_url . $match[0];
            }
        }
    }

    protected function include_dirs_to_pattern()
    {
        $input = explode(',', $this->include_dirs);
        if ($this->include_dirs == '' || count($input) < 1) {
            return 'wp\-content|wp\-includes';
        } else {
            return implode('|', array_map('quotemeta', array_map('trim', $input)));
        }
    }

    public function rewrite($content)
    {
        $dirs  = $this->include_dirs_to_pattern();
        $regex = '#(?<=[(\"\'])';
        $regex .= $this->rootrelative
        ? ('(?:' . quotemeta($this->blog_url) . ')?')
        : quotemeta($this->blog_url);
        $regex .= '/(?:((?:' . $dirs . ')[^\"\')]+)|([^/\"\']+\.[^/\"\')]+))(?=[\"\')])#';
        return preg_replace_callback($regex, array(&$this, 'rewrite_single'), $content);
    }

}